package com.ywgt.system.auth;

import com.ywgt.system.pojo.AuthUser;
import com.ywgt.system.pojo.Menu;
import com.ywgt.system.service.MenuService;
import com.ywgt.utils.JWTUtil;
import com.ywgt.utils.WriteJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 认证成功统一处理类
 */
@Component
public class SuccessfulAuthentication extends WriteJson implements AuthenticationSuccessHandler {

    @Autowired
    private MenuService menuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Object principal = authentication.getPrincipal();
        if (principal instanceof AuthUser){
            AuthUser authUser=(AuthUser) principal;
            String username = authUser.getUsername();
            List<Menu> menus = menuService.getMenuByUsername(username);
            String token = JWTUtil.getToken(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 15),
                    username, null);
            Map<String,Object> info =new HashMap<>();
            info.put("username",username);
            info.put("data",token);
            info.put("success",true);
            info.put("menus",menus);
            info.put("auth",authUser.getAuthorities());
            write(httpServletRequest,httpServletResponse,info);
        }
    }
}
